<template>
  <div class="change-avatar-app has-header">
    <img :src="showPicture" class="change-avatar-img">
    <div class="change-avatar-option touch-active" @click="capturePhoto('picture')">从相册选一张</div>
    <div class="change-avatar-option touch-active" @click="capturePhoto()">拍一张照片</div>
  </div>
</template>
<script>
export default {
  name: 'change-avatar-app',
  props: {
    userPicture: {
      default: null
    }
  },
  data() {
    return {
      capturedPhoto: null
    }
  },
  computed: {
    showPicture() {
      return this.capturedPhoto ? this.capturedPhoto : this.userPicture
    }
  },
  methods: {
    capturePhoto(sourceType) {
      var vm = this
      sourceType = sourceType ? navigator.camera.PictureSourceType.PHOTOLIBRARY : navigator.camera.PictureSourceType.CAMERA // use 0 or 1 maybe better
      //拍照并获取Base64编码的图像（quality : 存储图像的质量，范围是[0,100]）
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
        sourceType,
        quality: 50,
        allowEdit: true,
        cameraDirection: 1,
        // correctOrientation: true, // 会自动旋转照片，保证方向正确。
        destinationType: navigator.camera.DestinationType.FILE_URI // DATA_URL
      })

      //拍照成功
      function onPhotoDataSuccess(imageData) {
        vm.capturedPhoto = imageData
      }

      //拍照失败
      function onFail(message) {
        alert('拍照失败: ' + message)
      }
    }
  }
}

</script>
<style scoped lang="scss" rel="stylesheet/scss">
.change-avatar-app {
  text-align: center;
}

.change-avatar-img {
  // max-width: 100%;
  width: 100%;
  max-width: 7.5rem;
  max-height: 7.5rem;
}

.change-avatar-option {
  margin: 0.6rem 0.8rem 0;
  height: 0.8rem;
  line-height: 0.8rem;
  background-color: #fff;
  border-radius: 3px;
  border: 1px solid #eee;
}

</style>
